package com.atguigu.servlet;

import com.atguigu.utils.JedisPoolUtils;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;

import java.io.IOException;
import java.util.List;


public class SecKill_redis {
	
	private static final  org.slf4j.Logger logger =LoggerFactory.getLogger(SecKill_redis.class) ;

	public static void main(String[] args) {
		JedisPool jedisPool = JedisPoolUtils.getJedisPoolInstance();

		Jedis jedis = jedisPool.getResource();
		System.out.println(jedis.ping());

	}
	//ab -n 1000 -c 200  -p /opt/myRedis/postfile -T  "application/x-www-form-urlencoded" 192.168.16.28:8080/doseckill
	public static boolean doSecKill(String uid,String prodid) throws IOException {
		
		//拼接key
		String storekey ="Seckill:"+prodid+":store";
		String userKey ="Seckill:"+prodid+":user";
		//创建Jedis实例
		JedisPool jedisPool = JedisPoolUtils.getJedisPoolInstance();
		Jedis jedis = jedisPool.getResource();
		//获取redis中存储的库存信息
		String storeStr = jedis.get(storekey);
		//判断storeStr是否为null
		if(storeStr == null){
			//表示redis中没有库存信息,即秒杀还未开始
			System.out.println("秒杀还未开始" );
			JedisPoolUtils.release(jedisPool,jedis);
			return false;
		}
		//判断uid是否已经存到redis的set中,即判断该用户是否已经秒杀成功
		if(jedis.sismember(userKey,uid)){
			//表示uid已经存储到redis的set中,即该用户已经秒杀成功
			System.out.println("已经秒杀成功");
			JedisPoolUtils.release(jedisPool,jedis);
			return false;
		}
		//判断库存是否足够
		int store = Integer.parseInt(storeStr);
		if(store <=0){
			//库存不足
			System.out.println("已经抢光");
			JedisPoolUtils.release(jedisPool,jedis);
			return false;
		}
		//表示秒杀已经开始,该用户秒杀成功过,库存足够,既可以进行秒杀,-库存+用户
		jedis.decr(storekey);
		jedis.sadd(userKey,uid);
		System.out.println("秒杀成功" );
		JedisPoolUtils.release(jedisPool,jedis);
		return true;
	}
	
	
	
	
	
	
}
















